import tools from '@/utils/tools.js'

// 白名单
const whiteList = [
	'/pages/login/login',
	'/pages/main/main',
	'/pages/myPage/myPage'


]
export default async function() {
	const list = ['navigateTo', 'redirectTo', 'reLaunch', 'switchTab']
	// 添加全局路由拦截
	list.forEach(item => {
		uni.addInterceptor(item, {
			// 路由前拦截
			invoke(args) {
				const token = uni.getStorageSync('token')
				const url = args.url.split('?')[0]
				if (token) {
					if (args.url.includes('/pages/login/login')) {
						//跳转到首页
						uni.switchTab({
							url: '/pages/main/main',
						})
									return false
								}
						
					return args
				} else {
					
					let pass
					if (whiteList) {
						pass = whiteList.some((whiteItem) => {
							if (typeof(whiteItem) === 'object' && whiteItem.pattern) {
								return whiteItem.pattern.test(url)
							}
							return url === whiteItem
						})
					}
					console.log('到这里',pass,args)
					if (!pass) {
						uni.showToast({
							title: '请先登录',
							icon: 'none'
						})
						uni.redirectTo({
							url: "/pages/login/login"
						})
						return false
					}
					return args
				}
			},
			// 路由后拦截
			success(res) {},
			fail(err) {}
		});
	})
}